<?php

namespace app\index\controller;

use app\index\model\User as ModelUser;
use think\Controller;
use think\captcha\Captcha;
use think\Db;
use think\Validate;
use think\facade\Session;

class Admin extends Controller
{
    // 后台管理员登陆
    public function login()
    {
        if ($this->request->isPost()) {
            // 2. 接收用户得请求数据
            $data = $this->request->post();
            // 3. 数据校验
            // if (!captcha_check($this->request->post('captcha'))) {
            //     return $this->error('验证码错误');
            // }
            $validate = new Validate();
            if ($validate->scene('login')->check($data) == false) {
                return $this->error($validate->getError());
            }
            // 4. 数据库操作
            $$result = ModelUser::where('name', $data['name'])->find();
            if ($result === null) {
                return $this->error('用户名不存在');
            }
            if ($result['password'] != md5($data['password'])) {
                return $this->error('账号或密码错误');
            }
            // 5. 登陆成功 把用户信息存储到（session） 记录成功登陆的状态
            Session::set('admin', [
                'id' => $result['id'],
                'username' => $result['name']
            ]);
            // 6. 跳转 
            return $this->success('登陆成功', 'index/index/index');
        }
        return $this->fetch();
    }

    public function verify()
    {
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    30,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
            'useCurve'    =>    false
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
}
